#include <stdio.h>
#include <string.h>
#include "message.h"

static const char *MQTT_FORMAT = "+MQTTSUBRECV:%*d,\"" MQTT_SUB "\",%*d,%49[^:]:%49s";

// 初始化键值对
void msg_init(MessageKeyValue *pair, const char *key, const char *value)
{
    strncpy(pair->key, key, MAX_KEY_LENGTH - 1);
    pair->key[MAX_KEY_LENGTH - 1] = '\0';
    strncpy(pair->value, value, MAX_VALUE_LENGTH - 1);
    pair->value[MAX_VALUE_LENGTH - 1] = '\0';
}

// 生成要发送的消息，成功返回true，失败返回false
bool msg_generate(MessageKeyValue *pair, char *message, size_t message_size)
{
    if (pair == NULL || message == NULL || message_size == 0)
    {
        return false; // 输入参数无效
    }
    int written = snprintf(message, message_size, "%s:%s", pair->key, pair->value);

    if (written < 0 || (size_t)written >= message_size)
    {
        return false; // 输出缓冲区不足或发生错误
    }
    return true; // 生成成功
}

// 解析MQTT消息字符串
bool parse_mqtt_message(const char *message, MessageKeyValue *kvp)
{
    memset(kvp, 0, sizeof(MessageKeyValue));
    int ret = sscanf(message, MQTT_FORMAT, kvp->key, kvp->value);
    if (ret == 2)
    {
        return true;
    }
    return false;
}
